import btceapi
import datetime
import time
import pdb

KEYS_FNAME='mykeys'

engine = None
g_orders = {}

def reset():
    global engine
    handler = btceapi.KeyHandler(KEYS_FNAME)
    if len(handler.keys) != 1: raise RuntimeError('bidder::reset: failed to load keys from ' + KEYS_FNAME)
    engine = btceapi.TradeAPI(handler.keys[0], handler)

def getinfo():
    con = btceapi.BTCEConnection()
    ret = engine.getInfo(con)
    return ret

def runActiveBids():
    global g_orders
    noAnyBidFlag = True
    winner = None
    isParent = False

    con = btceapi.BTCEConnection()
    orders = engine.activeOrders('ltc_usd', con)
    if len(g_orders) == 0:
        for o in orders:
            o.rm_id = 0
            o.nonce = 0
            g_orders[o.order_id] = o
            print "runActiveBids: init: %s,%d,%s,%s,%f,%f,%d" % (str(o.timestamp_created), int(o.order_id), str(o.pair), str(o.type), float(o.amount), float(o.rate), int(o.status))
        print "runActiveBids: noAnyBidFlag=True with %d active bids" % len(g_orders)
        return (noAnyBidFlag, winner, isParent)
    active = set()
    for o in orders: active.add(o.order_id)
    nonce = 0
    order_id = 0
    for k, v in g_orders.iteritems():
        if (not k in active) and (v.nonce > nonce):
            nonce = v.nonce
            order_id = k
    noAnyBidFlag = False
    if order_id == 0:
        print "runActiveBids: no any winner found with %d active bids" % len(g_orders)
        return (noAnyBidFlag, winner, isParent)
    winner = g_orders.pop(order_id)
    isParent = True
    for k, v in g_orders.iteritems():
        if v.nonce > nonce: isParent = False
    o = winner
    print "runActiveBids: winner(%d): %s,%d,%s,%s,%f,%f,%d" % (int(isParent), str(o.timestamp_created), int(o.order_id), str(o.pair), str(o.type), float(o.amount), float(o.rate), int(o.status))
    return (noAnyBidFlag, winner, isParent)

def bidpair(rate, chunkLTC, chunkUSD, percent, optype=None):
    con = btceapi.BTCEConnection()
    #pdb.set_trace()

    sellRate = float(rate) + float(rate)*float(percent)
    sellAmount = chunkLTC
    while True:
        sell  = engine.trade('ltc_usd', 'sell', sellRate, sellAmount)
        if sell.order_id == 0:
            print 'bidpair: sell order_id is null - continue'
            continue
        break

    buyRate = float(rate) - float(rate)*float(percent)
    buyAmount = chunkUSD
    while True:
        buy = engine.trade('ltc_usd', 'buy', buyRate, buyAmount)
        if buy.order_id == 0:
            print 'bidpair: buy order_id is null - continue'
            continue
        break

    sellItem = btceapi.trade.OrderItem(sell.order_id, 
                                       {
                                        'pair':'ltc_usd',
                                        'type':'sell',
                                        'amount':sellAmount,
                                        'rate':sellRate,
                                        'timestamp_created':time.time(),
                                        'status':0,
                                       })
    nonce = engine.handler._keys[engine.key].nonce
    if optype is None or optype == 'buy':
        sellItem.rm_id = buy.order_id
    else:
        sellItem.rm_id = 0
    sellItem.nonce = nonce
    o = sellItem
    print "bidpair: %s,%d--%d,%s,%s,%f,%f,%d" % (str(o.timestamp_created), int(o.order_id), int(o.rm_id), str(o.pair), str(o.type), float(o.amount), float(o.rate), int(o.status))

    buyItem = btceapi.trade.OrderItem(buy.order_id,
                                      {
                                        'pair':'ltc_usd',
                                        'type':'buy',
                                        'amount':buyAmount,
                                        'rate':buyRate,
                                        'timestamp_created':time.time(),
                                        'status':0,
                                        'rm_id':0
                                      })
    if optype is None or optype == 'sell':
        buyItem.rm_id = sell.order_id
    else:
        buyItem.rm_id = 0
    buyItem.nonce = nonce
    o = buyItem
    print "bidpair: %s,%d--%d,%s,%s,%f,%f,%d" % (str(o.timestamp_created), int(o.order_id), int(o.rm_id), str(o.pair), str(o.type), float(o.amount), float(o.rate), int(o.status))
    g_orders[sell.order_id] = sellItem
    g_orders[buy.order_id] = buyItem

def bidrm(order_id):
    con = btceapi.BTCEConnection()
    res = engine.cancelOrder(order_id, con)
    g_orders.pop(res.order_id)
    print "bidrm: cancelled order %d" % res.order_id

if __name__ == '__main__':
    import pdb
    reset()
    info = getinfo()
    pdb.set_trace()
